using System;
using System.Collections.Generic;
using System.Text;
using SSRSDeployer.ReportService2005;
using SSRSDeployer.Properties;

namespace SSRSDeployer
{
    public class DatasourceDeployer : ReportingServiceDeployer
    {
        public DatasourceDeployer(Dictionary<string, string> arguments) : base(arguments) { }

        protected override void ValidateArguments()
        {
            if (string.IsNullOrEmpty(DatasourceName))
                throw new NullReferenceException(Resources.NoDatasource);
            if (string.IsNullOrEmpty(ConnectionString))
                throw new NullReferenceException(Resources.NoConnectionString);
        }

        public string DatasourceName
        {
            get { return Arguments["/idsc:"]; }
        }

        public string ConnectionString
        {
            get { return Arguments["/connectionstring:"]; }
        }

        public string Username
        {
            get { return Arguments["/username:"]; }
        }

        public string Password
        {
            get { return Arguments["/password:"]; }
        }

        private CredentialRetrievalEnum CredentialRetrieval
        {
            get
            {
                CredentialRetrievalEnum result = CredentialRetrievalEnum.Integrated;
                if (!string.IsNullOrEmpty(Username) && !string.IsNullOrEmpty(Password))
                    result = CredentialRetrievalEnum.Store;
                return result;
            }
        }

        public override void Deploy()
        {
            DataSourceDefinition definition = new DataSourceDefinition();
            definition.CredentialRetrieval = CredentialRetrieval;
            definition.ConnectString = ConnectionString;
            definition.Enabled = true;
            definition.EnabledSpecified = true;
            definition.Extension = "SQL";
            definition.ImpersonateUser = false;
            definition.ImpersonateUserSpecified = true; ///Use the default prompt string.
            definition.Prompt = null;
            definition.WindowsCredentials = false;
            definition.UserName = Username;
            definition.Password = Password;
            definition.WindowsCredentials = (CredentialRetrieval == CredentialRetrievalEnum.Store);
            try
            {
                if (this.CheckIfExists(ItemTypeEnum.DataSource, Parent, DatasourceName))
                    DeleteItem(Parent, DatasourceName);
                _rs.CreateDataSource(DatasourceName, Parent, true, definition, null);
                Console.WriteLine(Resources.DatasourcePublishSuccess, DatasourceName);
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}
